<template>
  <div class="login_box">
    <div class="login">
      <el-form
        label-width="70px"
        :model="loginForm"
        :rules="loginFormRules"
        ref="loginFormRef"
        class="login_form"
      >
        <el-form-item label="账号：" prop="username">
          <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password"></el-input>
        </el-form-item>
        <el-form-item label-width="0px" class="form_btn">
          <el-button type="primary" @click="login('loginFormRef')">登录</el-button>
          <el-button type="danger" @click="resetLoginForm('loginFormRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //登录表单的数据绑定对象
      loginForm: {
        username: 'admin',
        password: '123456',
      },
      //登录表单验证规则对象
      loginFormRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 6 到 18 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    resetLoginForm(loginFormRef) {
      this.$refs[loginFormRef].resetFields()
    },
    login(loginFormRef) {
      this.$refs[loginFormRef].validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status != 200) return this.$message.error('登录失败！')
        this.$message.success('登录成功！')
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    },
  },
}
</script>

<style lang="less" scoped>
.login_box {
  background: #2b4b6b;
  height: 100%;
}
.login {
  width: 450px;
  height: 300px;
  background: #fff;
  border-radius: 5px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.login_form {
  position: absolute;
  width: 100%;
  padding-right: 20px;
  top: 70px;
  box-sizing: border-box;
}
.form_btn {
  display: flex;
  justify-content: center;
  padding: 30px 0;
  box-sizing: border-box;
}
</style>
